<!-- 计划转生产委外 -->
<template>
  <pageHeader
    :title="title"
    :breadCrumb="['工厂建模', '生产BOM管理', '创建产品委外']"
    :show-back="true"
  >
    <template #buts>
      <a-button
        v-if="form.list.state >= 2"
        style="background: #e8f7ff; color: #518cff; margin-right: 20px"
        @click="generateBarCode"
      >
        <template #icon><icon-settings size="18" /> </template>
        <template #default>生成条码 </template>
      </a-button>
    </template>
    <template #footer>
      <a-space :size="20">
        <a-button
          type="primary"
          @click="handleOk"
          v-if="type === 'add' || type === 'edit'"
          >提交</a-button
        >
      </a-space>
    </template>
    <div id="QecodeContent">
      <a-spin :loading="loading" class="cantainer">
        <div class="tab">基本信息</div>
        <a-form :model="form.list" ref="formRef" auto-label-width>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="周计划单号"
                label-col-flex="100px"
              >
                <a-select
                  :disabled="type !== 'add'"
                  v-model="form.list.planId"
                  :style="{ width: '320px' }"
                  placeholder="请选择 ..."
                  @change="getPlanInfo"
                >
                  <a-option
                    v-for="item in planList"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.planCode }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="物料编码"
                label-col-flex="100px"
              >
                <a-input
                  disabled
                  :style="{ width: '320px' }"
                  v-model="form.list.materialNumber"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="物料名称"
                label-col-flex="100px"
              >
                <a-input
                  disabled
                  :style="{ width: '320px' }"
                  v-model="form.list.materialName"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="供  应  商"
                label-col-flex="100px"
              >
                <a-select
                  :disabled="type !== 'add' && type !== 'edit'"
                  v-model="form.list.supplierId"
                  :style="{ width: '320px' }"
                  placeholder="请选择 ..."
                >
                  <a-option
                    v-for="item in SupplierInfo"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="已委外数量"
                label-col-flex="100px"
              >
                <a-input
                  disabled
                  :style="{ width: '320px' }"
                  v-model="form.list.outsourcingAmount"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="本次委外数量"
                label-col-flex="100px"
                field="amount"
                required
              >
                <a-input-number
                  :min="1"
                  disabled
                  :style="{ width: '320px' }"
                  :max="form.list.totalNum - form.list.outsourcingAmount"
                  v-model="form.list.amount"
                  @change="changeAmount"
                  placeholder="请输入委外数量"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="加工费(含税)"
                label-col-flex="100px"
              >
                <a-input-number
                  :min="1"
                  :disabled="type !== 'add' && type !== 'edit'"
                  :style="{ width: '320px' }"
                  v-model="form.list.unitPrice"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                field="rate"
                label="税率"
                label-col-flex="100px"
                required
              >
                <a-input-number
                  :min="1"
                  :style="{ width: '320px' }"
                  :disabled="type !== 'add' && type !== 'edit'"
                  v-model="form.list.rate"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="含税合计"
                label-col-flex="100px"
              >
                <a-input-number
                  :min="1"
                  :style="{ width: '320px' }"
                  :disabled="type !== 'add' && type !== 'edit'"
                  v-model="form.list.totalPrice"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="form.list.itemState === 1" :gutter="16">
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="收货人姓名"
                label-col-flex="100px"
              >
                <a-input
                  :style="{ width: '320px' }"
                  :disabled="type !== 'add' && type !== 'edit'"
                  v-model="form.list.consigneeName"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="收货人电话"
                label-col-flex="100px"
              >
                <a-input
                  :style="{ width: '320px' }"
                  v-model="form.list.consigneePhone"
                  :disabled="type !== 'add' && type !== 'edit'"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                label="收货地址"
                label-col-flex="100px"
              >
                <a-input
                  :style="{ width: '320px' }"
                  v-model="form.list.consigneeAddress"
                  :disabled="type !== 'add' && type !== 'edit'"
                  placeholder="please enter..."
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item
                field="outsourcingDate"
                :show-colon="true"
                label="委外日期"
                label-col-flex="100px"
              >
                <a-date-picker
                  style="width: 330px; margin: 0 24px 24px 0"
                  show-time
                  :disabled="type !== 'add' && type !== 'edit'"
                  :time-picker-props="{ defaultValue: '09:09:06' }"
                  format="YYYY-MM-DD HH:mm:ss"
                  v-model="form.list.outsourcingDate"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :show-colon="true"
                field="entryDate"
                label="收货日期"
                label-col-flex="100px"
              >
                <a-date-picker
                  style="width: 330px; margin: 0 24px 24px 0"
                  show-time
                  :disabled="type !== 'add' && type !== 'edit'"
                  :time-picker-props="{ defaultValue: '09:09:06' }"
                  format="YYYY-MM-DD HH:mm:ss"
                  v-model="form.list.entryDate"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div class="tab"
          ><a-space
            ><div>附加物料清单</div
            ><a-switch
              :checked-value="1"
              :unchecked-value="2"
              v-model="form.list.itemState"
              :disabled="type !== 'add'"
              @change="EnableInventory"
            >
              <template #checked> ON </template>
              <template #unchecked> OFF </template>
            </a-switch></a-space
          >
        </div>
        <a-divider />

        <a-table
          :stripe="true"
          :dordered="{
            headerCell: true,
          }"
          :data="form.list.item"
          :scroll="scroll"
          :pagination="false"
        >
          <template #columns>
            <a-table-column
              title="物料编码"
              :width="100"
              align="center"
              data-index="managementNumber"
            ></a-table-column>
            <a-table-column
              title="物料名称"
              :width="100"
              align="center"
              data-index="managementName"
            ></a-table-column>
            <a-table-column
              v-if="type === 'add'"
              title="换算率"
              :width="100"
              align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.dosage" /> </template
            ></a-table-column>
            <a-table-column title="规格型号" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.spec" /> </template
            ></a-table-column>
            <a-table-column
              title="空闲数量"
              v-if="type === 'add'"
              :width="100"
              align="center"
              ><template #cell="{ record }">
                <a-input disabled v-model="record.freeAmount" /> </template
            ></a-table-column>
            <a-table-column title="推荐委外数量" :width="100" align="center"
              ><template #cell="{ record }">
                <a-input-number
                  :min="1"
                  v-model="record.amount"
                  disabled
                /> </template
            ></a-table-column>
          </template>
        </a-table>

        <div v-if="form.list.state >= 2" class="tab" style="margin-top: 20px"
          ><a-space><div>条码记录</div></a-space>
        </div>
        <a-table
          v-if="form.list.state >= 2"
          :stripe="true"
          :dordered="{
            headerCell: true,
          }"
          :data="form.list.barcodes"
          :scroll="scroll"
          :pagination="false"
        >
          <template #columns>
            <a-table-column
              title="物料编码"
              :width="100"
              align="center"
              data-index="managementNumber"
              ><template #cell="{ record }"
                ><QRcode
                  ref="qrcode"
                  :qr-url="`${record.content}`"
                  :qr-text="`${record.content}`"
                /> </template
            ></a-table-column>
            <a-table-column title="条码格式" :width="100" align="center"
              ><template #cell="{}"> {{ '二维码' }}</template></a-table-column
            >

            <a-table-column title="条码编号" :width="100" align="center">
              <template #cell="{ record }">
                <a-textarea
                  v-model="record.content"
                  placeholder="Please enxter something"
                  disabled
                  allow-clear
                /> </template
            ></a-table-column>

            <a-table-column
              :width="100"
              title="启用状态"
              data-index="tier"
              align="center"
              ><template #cell="{ record }">
                <a-typography-text type="success">
                  {{ record.state === 1 ? '已启用' : '' }}
                </a-typography-text>
              </template>
            </a-table-column>
            <a-table-column
              :width="100"
              title="操作"
              data-index="tier"
              align="center"
              ><template #cell="{ record, rowIndex }">
                <a-space>
                  <a-dropdown @select="handleSelect">
                    <a-button type="primary">更多功能</a-button>
                    <template #content>
                      <a-space direction="vertical" fill>
                        <a-button type="text">条码打印</a-button>
                        <a-button type="text" @click="bb(rowIndex)"
                          >条码下载</a-button
                        >
                        <a-popconfirm
                          content="确认删除?"
                          type="error"
                          @ok="delQrcode(record.id)"
                        >
                          <a-button type="text" status="danger"
                            >条码删除</a-button
                          >
                        </a-popconfirm>
                      </a-space>
                    </template>
                  </a-dropdown>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-spin>
    </div>
  </pageHeader>

  <BarCode
    v-if="modelVisible"
    v-model:visible="modelVisible"
    :orderInfo="form.list"
    @addBarcode="addBarcode"
  />
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, watchEffect } from 'vue';
  import {
    getOutsourcingSupplier,
    postOutsourcing,
    getOutsourcingOne,
    putOutsourcingOne,
  } from '@/api/produce-management/production-operation/index';
  import { getBarcode, delarcode } from '@/api/barcode';
  import { getSupplierInfo } from '@/api/buy-management/supplier-management/supplier-primary-list/index';
  import { GetProducePlanPage } from '@/api/produce-management/OrderPlanning';
  import { Message } from '@arco-design/web-vue';
  import { useRoute, useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import BarCode from './BarCode.vue';

  const modelVisible = ref(false);
  const formRef = ref();
  let route = useRoute();
  let router = useRouter();
  let loading = ref(false);
  let type = route.query.type;
  let title = route.query.name;
  const form = reactive<any>({
    list: {
      name: '1',
      item: [],
      outsourcingType: 1, // 委外类型
      planAmount: 0,
      planId: null,
      amount: 0,
      state: 1,
      usedQuantity: 0,
    },
  });
  const SupplierInfo = ref([]);

  const materialData = ref([]);
  const newDosage = ref();

  const TreeData = (data: any, parentMultiplier: number) => {
    const currentMultiplier = parentMultiplier * data.dosage;
    if (!data.children) {
      return [{ ...data, dosage: currentMultiplier }];
    }
    const result: any = [];
    data.children.forEach((item: any) => {
      const childResult = TreeData(item, currentMultiplier);
      result.push(...childResult);
    });
    return result;
  };

  const planList = ref();
  const getPlanList = async () => {
    try {
      const res = await GetProducePlanPage({
        page: 1,
        size: -1,
        type: 1,
      });
      planList.value = res.content.filter((i) => i.materialAttribute === 2);
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getPlanList();

  const getPlanInfo = async (id: any) => {
    const newArr = planList.value.filter((item) => item.id === id);

    Object.assign(form.list, newArr[0]);
    form.list.planId = form.list.id;
    form.list.managementId = form.list.productId;
    form.list.state = 1;
    delete form.list.id;
    const SupplierRes = await getSupplierInfo({
      id: form.list.productId,
    });
    SupplierInfo.value = SupplierRes;
  };

  const EnableInventory = async (e) => {
    try {
      if (e === 1) {
        if (!form.list.productId) {
          Message.warning('请选择关联计划单');
          form.list.itemState = 2;
          return;
        }
        let newArr: any = [];
        const res = await getOutsourcingSupplier({ id: form.list.productId });
        form.list.item = TreeData(res, res.dosage);
        form.list.item.forEach((ele: any) => {
          const index = newArr.findIndex((i: any) => ele.bomName === i.bomName);
          if (index === -1) {
            newArr.push({ ...ele });
          } else {
            newArr[index].dosage += ele.dosage;
          }
        });
        form.list.item = newArr;
        form.list.item.forEach((item: any) => {
          delete item.id;
        });
        if (form.list.amount !== null) {
          form.list.item.forEach((item: any) => {
            item.amount = form.list.amount * Number(item.dosage);
          });
        }
      } else {
        form.list.item = [];
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  watchEffect(() => {
    if (form.list.unitPrice && form.list.amount) {
      form.list.totalPrice = form.list.unitPrice * form.list.amount;
    }
  });

  const changeAmount = () => {
    if (form.list.item && form.list.amount) {
      form.list.item.forEach((item: any) => {
        item.amount = form.list.amount * Number(item.dosage);
      });
    }
  };

  const handleOk = () => {
    formRef.value.validate(async (res: any) => {
      if (!res) {
        if (type === 'edit') {
          form.list.outsourcingDate = new Date(
            form.list.outsourcingDate
          ).toJSON();
          form.list.entryDate = new Date(form.list.entryDate).toJSON();

          await putOutsourcingOne({ ...form.list });
          router.push({ name: 'ProductOutsourcing' });
        } else {
          if (form.list.produceNumber === form.list.outsourcingAmount) {
            Message.warning(`该条周计划已完成生产委外`);
            return;
          }
          form.list.outsourcingDate = new Date(
            form.list.outsourcingDate
          ).toJSON();
          form.list.entryDate = new Date(form.list.entryDate).toJSON();
          form.list.item.forEach((item) => {
            if (item.totalAmount < item.safetyAmount || !item.totalAmount) {
              Message.warning(
                `${item.managementName}产品的总库存量已低至安全库存量，请及时补充`
              );
            }
          });
          await postOutsourcing({ ...form.list });
          router.push({ name: 'ProductOutsourcing' });
        }
      }
    });
  };

  const getData = async (id?: number) => {
    try {
      const res = await getOutsourcingOne({ id });
      const SupplierRes = await getSupplierInfo({
        id: res.managementId,
      });
      SupplierInfo.value = SupplierRes;
      Object.assign(form.list, res);
      form.list.materialNumber = form.list.managementNumber;
      form.list.materialName = form.list.managementName;
      if (form.list.barcodes) {
        form.list.barcodes.forEach((ele: any) => {
          form.list.usedQuantity += ele.amount;
        });
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  onMounted(() => {
    if (type !== 'add') {
      getData(Number(route.query.id));
    }
  });

  const generateBarCode = () => {
    modelVisible.value = true;
  };

  const bb = (index: number) => {
    let canvas1 = document.getElementById('QecodeContent');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    let a = document.createElement('a');
    a.href = canvas[index].toDataURL('img/png');
    a.download = '二维码';
    a.click();
    Message.error('下载中，请稍后...');
  };

  const delQrcode = async (id?: number) => {
    await delarcode({ id });
    getData();
  };

  const addBarcode = () => {
    getData(Number(route.query.id));
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
    margin-bottom: 150px;
  }
  .form {
    padding-left: 100px;
    padding-right: 100px;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 20px;
    font-size: 20px;
  }
  .orderBox {
    padding-left: 50px;
    // padding: 0px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
